/**
 * /lib/Utils.js
 * @author ayuanlmo
 * Created by ayuanlmo in 2022/06/30
 * **/

import MD5 from 'js-md5'

/**
 * @name {anyToString} 将常用数据类型转为string
 * @param [str] any 待转换的值
 * @return [String] 转换后的值
 * **/
export const anyToString = str => {
    if (typeof str === 'undefined')
        return '';
    else if (typeof str === 'object')
        return JSON.stringify(str);
    else if (typeof str === 'string' || typeof str === 'number' || typeof str === 'boolean')
        return `${str}`;
}

export const toFloat = str => parseFloat(str)

/**
 * @name {imgToBase64} 图片转base64数据
 * @param [url] 图片地址
 * @return [String] 图片base64数据
 * 图片文件大小不宜过大，会很耗性能
 * **/
export const imgToBase64 = url => {
    const xhr = new XMLHttpRequest();
    const fr = new FileReader();
    xhr.open('get', url, true);
    xhr.responseType = 'blob';
    xhr.onload = res => {
        const blob = res.response;
        fr.readAsDataURL(blob);
        fr.onload = e => {
            return e.target.result;
        }
    }
}

/**
 * @name {createElement} 创建元素
 * @return [Element] Element
 * **/
export const createElement = name => document.createElement(name);

/**
 * @name {getMd5} 获取MD5值
 * @param [str] String NotNull
 * @return [String] MD5 String
 * **/
export const getMd5 = str => MD5(str)

/**
 * @name {getWsUrl} 是否wss
 * @param [url] String NotNull
 * @return [String] WebSocket URL
 * 传入链接地址 http返回:ws://ayuan.fi || https 返回:wss://ayuan.fi
 * **/
export const getWsUrl = url => {
    const t = url.split(':');
    return `${t[0] === 'http' ? 'ws:' : 'wss:'}${t[1]}`
}

/**
 * @name {formatDate} 时间戳转日期 （YYYY-MM-DD）
 * @param [n] 传时间 new Date(parseInt('时间戳字符串'))
 * @param [hms] 时候需要时分秒
 * @return [String] '2021-06-19' 格式化后的时间
 * **/
export const formatDate = (n, hms = ![]) => {
    const year = n.getFullYear();
    const month = n.getMonth() + 1 < 10 ? `0${n.getMonth() + 1}` : n.getMonth() + 1;
    const date = n.getDate() < 10 ? `0${n.getDate()}` : n.getDate();
    const hour = n.getHours() < 10 ? `0${n.getHours()}` : n.getHours();
    const minute = n.getMinutes() < 10 ? `0${n.getMinutes()}` : n.getMinutes();
    const second = n.getSeconds() < 10 ? `0${n.getSeconds()}` : n.getSeconds();
    if (hms)
        return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    else
        return year + "-" + month + "-" + date + " ";
}

/**
 * @name {getTheCurrentStartAndEndTimestamp} 获取某天开始 和 结束 时间戳
 * @params {str} 时间 {String} '2021-01-21'
 * @return {Object} {start:'开始时间戳',end:'结束时间戳'}
 * **/
export const getTheCurrentStartAndEndTimestamp = str => {
    const now = new Date(str);//初始化时间
    return {
        start: now.setHours(0, 0, 0, 0),//开始时间
        end: now.setHours(23, 59, 59, 999),//结束时间
    }
}
/**
 * @name {jsonToUrlParameter} json转url查询
 * @param [obj] Object NotNull json对象 {}
 * @return [String] 转换后的url查询字符串 String 'id=ayuan&p=ayuanlmo'
 * **/
export const jsonToUrlParameter = obj => Object.keys(obj).map(function (key) {
    return `${encodeURIComponent(key) + "=" + encodeURIComponent(obj[key])}`;
}).join("&");

/**
 * @name {getFormData} 获得FormData
 * @param [params] Object NotNull
 * @return {FormData}
 * **/
export const getFormData = params => {
    const fd = new FormData();
    for (let i in params) {
        //此处判断一下 否则可能造成迭代异常
        if (params.hasOwnProperty(i))
            fd.append(i, params[i]);
    }
    return fd;
}

export const isHTTPS = url => {
    return url.split(':')[0] === 'https';
}
/**
 * 判断当前路由是否存在
 * @param to
 * @returns {boolean}
 */
export const hasRoute = (to)=>{
    let find = router.getRoutes().find(item => item.name === to.name);
    console.log("find:",find)
    return !!find;

}